package com.pzr.soccer.controller;


import com.pzr.soccer.model.R;
import com.pzr.soccer.model.Role;
import com.pzr.soccer.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.websocket.server.PathParam;
import java.time.LocalDate;

@RestController
@Slf4j
@RequestMapping("/user")
public class RoleController {

    @Autowired
    UserService userService;

    @Value("${client.name:soccer}")
    private String client;

    @PostMapping("/changeRoleExpired")
    public R<String> changeRoleExpired(@PathParam("userId") String userId, @PathParam("roleName") String roleName,
                                       @PathParam("expiredDate") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate expiredDate) {

        if (userService.changeRoleExpired(userId, roleName, expiredDate)) {
            return R.ok("change role expired date successfully!");
        } else {
            return R.fail("change role expired date Failed!");
        }

    }

    @PostMapping("/addRoleToUser")
    public R<String> addRoleToUser(@PathParam("userId") String userId, @PathParam("roleName") String roleName,
                                   @PathParam("expiredDate") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate expiredDate) {
        Role role = Role.build(roleName, expiredDate);
        if (role == null) {
            return R.fail("no such role name " + roleName);
        }
        role.setClient(client);
        if (userService.addRole(userId, role)) {
            return R.ok("add role successfully!");
        }
        return R.fail("add role Failed!");
    }

    @PostMapping("/removeRoleFromUser")
    public R<String> remove(@PathParam("userId") String userId, @PathParam("roleName") String roleName) {

        if (userService.removeRole(userId, roleName)) {
            return R.ok("remove role  successfully!");
        }
        return R.fail("remove role  faild!");
    }

}
